//
//  STRegisterViewController.m
//  赛拓
//
//  Created by 王磊 on 7/31/16.
//  Copyright © 2016 立金所. All rights reserved.
//

#import "STRegisterViewController.h"
#import "STCustomTF.h"
#import "STLoginViewController.h"
#import "STProtocolViewController.h"
#import "STTabbarViewController.h"
@interface STRegisterViewController ()<STBaseViewDelegate ,M80AttributedLabelDelegate>

@property (nonatomic ,strong) STCustomTF *phone;

@property (nonatomic ,strong) STCustomTF *verify;

@property (nonatomic ,strong) STCustomTF *pwd;

@property (nonatomic ,strong) NSTimer *timer;

@property (nonatomic ,assign) NSInteger count;

@property (nonatomic ,strong) M80AttributedLabel *protocolLabel;
@end
#define imageView_height 120 * ST_RATE
@implementation STRegisterViewController

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    if (self.timer) {
        
        [self.timer invalidate];
        
        self.timer = nil;
        
        [self.verify updateVerifyState:@"点击获取" isEnabled:true];
    }
    
    [self.phone clear];
    
    [self.verify clear];
    
    [self.pwd clear];
}
- (void)initSubviews {
    [super initSubviews];
    
    CGFloat height = 85 * ST_RATE;
    
    CGFloat left_margin = 40 * ST_RATE;
    
    self.view.backgroundColor = ST_WHITE_COLOR;
    
    [self.imageView makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(200 * ST_RATE);
        make.right.equalTo(- 200 * ST_RATE);
        make.top.equalTo(120 * ST_RATE);
        make.height.equalTo(imageView_height);
    }];
    
    self.imageView.image = [UIImage imageNamed:@"logo"];
    STCustomTF *phone = [STCustomTF instance];
    
    phone.iconImageName = @"手机";
    
    phone.mDelegate = self;
    
    self.phone = phone;
    
    phone.placeHolder = @"请输入手机号";
    
    phone.maxLength = 11;
    
    phone.tid = @"phone";
    
    phone.returnKeyType = UIReturnKeyNext;
    
    [self.view addSubview:phone];
    
    STCustomTF *verify = [STCustomTF instance];
    
    self.verify = verify;
    
    verify.isVerifyShow = false;
    
    verify.mDelegate = self;
    
    verify.maxLength = 4;
    
    verify.tid = @"verify";
    
    verify.iconImageName = @"验证码";
    
    verify.returnKeyType = UIReturnKeyNext;
    
    verify.placeHolder = @"请输入验证码";
    
    [self.view addSubview:verify];
    
    STCustomTF *pwd = [STCustomTF instance];
    
    self.pwd = pwd;
    
    pwd.mDelegate = self;
    
    pwd.tid = @"pwd";
    
    pwd.returnKeyType = UIReturnKeyDone;
    
    pwd.iconImageName = @"密码";
    
    pwd.maxLength = 18;
    
    pwd.secureTextEntry = true;
    
    pwd.placeHolder = @"请输入密码";
    
    [self.view addSubview:pwd];
    
    @WeakObj(self)
    [phone makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(selfWeak.imageView.mas_bottom).offset(90 * ST_RATE);
        make.height.equalTo(height);
        make.left.equalTo(left_margin);
        make.right.equalTo(-left_margin);
    }];
    
    [verify makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(phone.mas_bottom).offset(25 * ST_RATE);
        make.height.equalTo(height);
        make.left.equalTo(left_margin);
        make.right.equalTo(-left_margin);
    }];
    
    [pwd makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(verify.mas_bottom).offset(25 * ST_RATE);
        make.height.equalTo(height);
        make.left.equalTo(left_margin);
        make.right.equalTo(-left_margin);
    }];
    
    UIButton *regist = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [self.view addSubview:regist];
    
    [regist setTitle:@"确认注册" forState:UIControlStateNormal];
    
    [regist setTitle:@"确认注册" forState:UIControlStateHighlighted];
    
    regist.backgroundColor = ST_167EC0_COLOR;
    
    regist.layer.cornerRadius = height / 2;
    
    [regist makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(pwd.mas_left);
        make.top.equalTo(pwd.mas_bottom).offset(90 * ST_RATE);
        make.right.equalTo(pwd.mas_right);
        make.height.equalTo(height);
    }];
    
    UIButton *pro = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [self.view addSubview:pro];
    
    [pro setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    
    [pro setImage:[UIImage imageNamed:@""] forState:UIControlStateSelected];
    
    M80AttributedLabel *protocolLabel = [[M80AttributedLabel alloc]init];
    
    [self.view addSubview:protocolLabel];
    
    self.protocolLabel = protocolLabel;
    
    NSString *text = @"已阅读《赛拓相关协议》";
    
    [protocolLabel setAttributedText:[[NSAttributedString alloc]initWithString:text attributes:@{NSFontAttributeName: ST_13_FONT ,NSForegroundColorAttributeName: ST_999999_COLOR}] ];
    
    
    CGSize protocol_size = [NSString suitToSize:text withSize:CGSizeMake(999, 999) andFont:ST_13_FONT andLineSpacing:3];
    
    protocolLabel.underLineForLink = false;
    
    protocolLabel.delegate = self;
    
    NSRange range = [text rangeOfString:@"赛拓相关协议"];
    
    [protocolLabel addCustomLink:@"赛拓相关协议" forRange:range linkColor:ST_167EC0_COLOR];
    
    [protocolLabel makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerX.equalTo(0);
        make.top.equalTo(regist.mas_bottom).offset(10 * ST_RATE);
        make.width.equalTo(protocol_size.width);
        make.height.equalTo(protocol_size.height);
    }];
    
    M80AttributedLabel *login = [M80AttributedLabel new];
    
    [self.view addSubview:login];
    
    text = @"已有账号,立即登陆";
    
    [login setAttributedText:[[NSAttributedString alloc]initWithString:text attributes:@{NSFontAttributeName: ST_15_FONT ,NSForegroundColorAttributeName: ST_999999_COLOR}] ];
    
    login.delegate = self;
    
    login.underLineForLink = false;
    
    login.textAlignment = kCTTextAlignmentCenter;
    
    range = [text rangeOfString:@"立即登陆"];
    
    [login addCustomLink:@"立即登陆" forRange:range linkColor:ST_167EC0_COLOR];
    
    [login makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(pwd.mas_left);
        make.right.equalTo(pwd.mas_right);
        make.top.equalTo(protocolLabel.mas_bottom).offset(150 * ST_RATE);
        make.height.equalTo(height);
    }];
    
    [regist addTarget:self action:@selector(registTriggered) forControlEvents:UIControlEventTouchUpInside];
    
}

- (void)registTriggered {
    [self onItemClick:STItemClickTypeRegister withData:nil forIndexPath:nil];
}
- (void)m80AttributedLabel:(M80AttributedLabel *)label clickedOnLink:(id)linkData {
    
    if (label == self.protocolLabel) {
        [self onItemClick:STItemClickTypeRegisterProtocol withData:nil forIndexPath:nil];
    } else {
        
        [self onItemClick:STItemClickTypeLogin withData:nil forIndexPath:nil];
    }
    
}
- (void)onItemClick:(STItemClickType )itemType withData:(id)data forIndexPath:(NSIndexPath *)indexPath {
    @WeakObj(self)
    switch (itemType) {
        case STItemClickTypeRegister:
        {
            NSDictionary *dict;
            NSString *pushId = @"123123123";
            if (!self.type) {
                dict = @{@"phoneNum":self.phone.text,@"vcode":self.verify.text,@"password":self.pwd.text,@"fromType":@"2",@"pushId":pushId,@"deviceId":deviceId,@"os":deviceOS,@"model":deviceModels,@"resolution":deviceResolution};
            } else {
                
                dict = @{@"type":self.type,@"openId":self.openId,@"phoneNum":self.phone.text,@"vcode":self.verify.text,@"password":self.pwd.text,@"fromType":@"2",@"pushId":pushId,@"deviceId":deviceId,@"os":deviceOS,@"model":deviceModels,@"resolution":deviceResolution};
                
                
            }
            [SVProgressHUD showWithStatus:@"注册中...."];
            
            [[STHttpManager getInstance] requestWithUrlString:ST_HTTP_REGISTER andParams:dict andStartBlock:^BOOL{
                return true;
            } andSuccessBlock:^(NSString *rescode, NSString *msg, NSString *token, NSString *sysTime, id data, NSString *page) {
                
                if ([rescode isEqualToString:@"100"]) {
                    
                    [SVProgressHUD showSuccessWithStatus:@"注册成功"];
                    
                    STAccountBean *account = [STAccountBean mj_objectWithKeyValues:data];
                    [account save];
                    
                    selfWeak.mDelegate.accountBean = account;
                    
                    STTabbarViewController *tab = [STTabbarViewController instance];
                    
                    [selfWeak presentViewController:tab animated:true completion:nil];
                }else {
                    
                    [SVProgressHUD showInfoWithStatus:msg];
                }
                
                
            } andFailureBlock:^BOOL{
                
                [SVProgressHUD  popActivity];
                return true;
            }];
            
            
            
            
        }
            break;
        case STItemClickTypeLogin:
        {
            BOOL flag = false;
            for (UIViewController *vc in self.navigationController.childViewControllers) {
                if ([vc isKindOfClass:[STLoginViewController class]]) {
                    flag = true;
                    [selfWeak.navigationController popViewControllerAnimated:true];
                }
            }
            if (!flag) {
                
                STLoginViewController *login = [STLoginViewController instance];
                
                [selfWeak.navigationController pushViewController:login animated:true];
            }
        }
            break;
        case STItemClickTypeRegisterProtocol:
        {
            STProtocolViewController *pro = [STProtocolViewController instance];
            
            [self.navigationController pushViewController:pro animated:true];
        }
            break;
        case STItemClickTypeVerify:
        {
            self.count = 60;
            @WeakObj(self)
            if (self.phone.text.length) {
                
                [[STHttpManager getInstance] requestWithUrlString:ST_HTTP_GETVCODE andParams:@{@"phoneNum":self.phone.text} andStartBlock:^BOOL{
                    return true;
                } andSuccessBlock:^(NSString *rescode, NSString *msg, NSString *token, NSString *sysTime, id data, NSString *page) {
                    if ([rescode  isEqualToString:@"100"]) {
                        
                        selfWeak.timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timeChanged:)userInfo:nil repeats:true];
                        
                        [[NSRunLoop currentRunLoop]addTimer:selfWeak.timer forMode:NSDefaultRunLoopMode];
                        
                    } else {
                        
                        [SVProgressHUD showInfoWithStatus:msg];
                    }
                    
                } andFailureBlock:^BOOL{
                    
                    return true;
                }];
            } else {
                
                [SVProgressHUD showInfoWithStatus:@"手机号不能为空"];
            }
            
        }
            break;
        case STItemClickTypeReturnKey:
            if ([data isEqualToString:@"phone"]) {
                
                [self.phone resignFirstResponder];
                
                [self.verify becomeFirstResponder];
                
            }else if ([data isEqualToString:@"verify"]) {
                
                [self.verify resignFirstResponder];
                
                [self.pwd becomeFirstResponder];
            } else {
                
                [self.pwd resignFirstResponder];
                
                [self registTriggered];
            }
            break;
            
        default:
            break;
    }
    
}
- (void)timeChanged:(NSTimer *)timer {
    self.count--;
    
    BOOL enbled = false;
    NSString *text = @"";
    if (self.count <= 0) {
        [self.timer invalidate];
        self.timer = nil;
        enbled = true;
        text = @"点击获取";
        
    }else {
        
        text = [NSString stringWithFormat:@"(%lds)",self.count];
    }
    
    [self.verify updateVerifyState:text isEnabled:enbled];
    
}


@end
